/*
 * @Author: xuetao 3168581151@qq.com
 * @Date: 2025-02-14
 * @LastEditors: xuetao 3168581151@qq.com
 * @LastEditTime: 2025-02-25
 * @Description: 验证码组件
 */

import 'package:chat_client/services/api_service.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';

// 工具
import 'package:chat_client/utils/media_tools.dart';

class Captcha extends StatefulWidget {
  // 回调函数的方式在父组件中拿到 _captchaUid
  final Function(String?) onCaptchaUidChanged;

  const Captcha({super.key, required this.onCaptchaUidChanged});

  @override
  CaptchaState createState() => CaptchaState();
}

class CaptchaState extends State<Captcha> {
  final ApiService apiService = ApiService.instance;

  /// 获取/刷新验证码
  Future _getCaptcha({String? oldUid}) async {
    final response = await apiService.post('/auth/capcha', {'oldUid': oldUid});
    return response['data'];
  }

  String? _svgString;
  String? _captchaUid;

  @override
  void initState() {
    super.initState();
    _setCaptcha();
  }

  _setCaptcha({String? uid}) async {
    final captcha = await _getCaptcha(oldUid: uid);
    setState(() {
      _svgString = captcha['captcha'];
      _captchaUid = captcha['captchaUid'];
    });
    // 将 _captchaUid 传递给父组件
    widget.onCaptchaUidChanged(_captchaUid);
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        _setCaptcha(uid: _captchaUid);
      },
      child: kIsWeb
          ? Container(
              height: 44,
              width: 88,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(4),
              ),
              child: _svgString != null
                  ? SvgPicture.string(_svgString!)
                  : CircularProgressIndicator(), // 数据加载中显示一个加载指示器,
            )
          : Container(
              height: 62,
              width: getMediaWidth(context) / 3,
              decoration: BoxDecoration(
                  color: Colors.white, borderRadius: BorderRadius.circular(4)),
              child: _svgString != null
                  ? SvgPicture.string(_svgString!)
                  : CircularProgressIndicator(), // 数据加载中显示一个加载指示器,
            ),
    );
  }
}
